<?php
/**
 * Created by PhpStorm.
 * User: front
 * Date: 2018/8/3
 * Time: 16:39
 */

namespace App\Services;

use App\Exceptions\ApiException;
use Facebook\Facebook;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

/*
 * 第三方登录
 **/
class OauthService
{
    public $oauth_type_wx = 'wx';
    public $oauth_type_fb = 'fb';
    public $oauth_type_fb_hk = 'fb_hk';
    public $oauth_type_wxm = 'wxm';
    public $oauth_type_qq = 'qq';
    public $oauth_type_wb = 'wb';

    /*
     * 创建授权url
     * */
    public function create_oauth_wx_url()
    {
        $auth = config('auth.weixin');
        $jump_url = unescape(IT('jump_url'));
        $uid = IT('uid', 0);
        $share_type =  IT('share_type', 'main');// main: 官网   mediadetail:视频详情
        $channel =  IT('channel', '0');

        $media_id = IT('media_id', 0);
        $api_url = urlencode($auth['api_url'] . 'api/Oauth_login_weixin?share_type=' . $share_type ."&uid=".$uid."&media_id=".$media_id.'&channel='.$channel);
        $scope = ($share_type == 'main') ? 'snsapi_userinfo' : 'snsapi_base';
        $redirect_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $auth['appid'] . '&redirect_uri=' . $api_url . '&response_type=code&scope='.$scope.'&state=&connect_redirect=1#wechat_redirect';

        return $redirect_url;
    }

    /*
     * 创建facebook 授权url
     * */
    public function create_oauth_fb_hk_url()
    {
        $uid = IT('uid', 0);
        $media_id = IT('media_id', 0);
        $share_type = IT('share_type','index');
        $client_ip = get_ip();
        $expires_in = 300;
        $redis = Redis::connection('redis_hk');
        $redis->setex('share_params:'.md5($client_ip), $expires_in, json_encode(['share_type'=>$share_type, 'uid'=>$uid, 'media_id'=>$media_id]));

        $fb = new Facebook([
            'app_id' => config('basic.fb_config.fb_app_id'),
            'app_secret' => config('basic.fb_config.fb_app_secret'),
            'default_graph_version' => config('basic.fb_config.fb_default_graph_version'),
        ]);
        $helper = $fb->getRedirectLoginHelper();
        $permissions = ['public_profile','email']; // Optional permissions
        $callBackUrl = config('basic.fb_config.fb_call_back_url'). '/api/oauth_fb_callback';
        $loginUrl = $helper->getLoginUrl($callBackUrl, $permissions);
        return $loginUrl;
    }

    /*
     * facebook 中转授权
     * */
    public function oauth_transfer_fb($params)
    {
        if(isset($params['s']))
            unset($params['s']);
        if(isset($params['channel']) && $params['channel'] == 'fb')
            $params['channel'] = 'fb_hk';
        $redirect_url = config('basic.transfer_url').'/api/Sharing_links';
        $redirect_url .= '?'.http_build_query($params);
        return $redirect_url;
    }

}